package com.apesay.core;

import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;

public class ConfigUtils {

	private static final String CONFIG_NAME = "plugins.config.properties";
	private static final Properties properties = new Properties();
	private static final HashMap<String,Boolean> map = new HashMap<String,Boolean>();

	static {
		System.out.println("========ConfigUtils===========");
		InputStream in = ClassLoader.getSystemResourceAsStream(CONFIG_NAME);
		try {
			if(in==null){
				URL resource = ConfigUtils.class.getClassLoader().getResource(CONFIG_NAME);
				if (null!=resource){
					String filename = new URI(resource.toString()).toString();
					File file = new File(filename.replace("file:", ""));
					in = new FileInputStream(file);
					if (in!=null) {
						initMap(in);
					}
				}
			}else{
				initMap(in);
			}
		} catch (URISyntaxException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void initMap(InputStream in) throws IOException {
		properties.load(in);
		Enumeration en = properties.propertyNames(); //得到配置文件的名字
		while(en.hasMoreElements()) {
			String strKey = (String) en.nextElement();
			Boolean strValue = Boolean.valueOf(properties.getProperty(strKey));
			map.put(strKey,strValue);
		}
	}

	public static Boolean getValue(String key,Boolean defalutValue) {
		Boolean result = map.get(key);
		if (null==result) {
			result = defalutValue;
		}
		return result;
	}
}
